﻿
namespace HSS.Xaml.UI.Interactivity
{
	#region Using Directives
	using System.Windows.Controls;
	using System.Windows.Interactivity;
	#endregion

	#region DataGridCopyCellTrigger
	/// <summary>
	/// A Trigger that forces a Copy operation for a DataGrid to only copy the current cell versus the entire row.
	/// </summary>
	public sealed class DataGridCopyCellTrigger : TriggerBase<DataGrid>
	{
		/// <summary>
		/// Called when the Trigger is being attached to the AssociatedObject.
		/// </summary>
		protected override void OnAttached()
		{
			base.OnAttached();
			if (this.AssociatedObject is DataGrid)
				this.AssociatedObject.CopyingRowClipboardContent += DataGrid_CopyingRowClipboardContent;
		}
		/// <summary>
		/// Called when the Trigger is being detached from the AssociatedObject.
		/// </summary>
		protected override void OnDetaching()
		{
			this.AssociatedObject.CopyingRowClipboardContent -= DataGrid_CopyingRowClipboardContent;
			if (null != _clipboardContentControl)
			{
				_clipboardContentControl.ClearValue(ContentControl.ContentProperty);
				_clipboardContentControl = null;
			}
			base.OnDetaching();
		}

		private void DataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
		{
			var dtg = sender as DataGrid;
			e.ClipboardRowContent.Clear();
			var column = dtg.CurrentColumn;
			var cellValue = this.GetCellValue(e.Item, column.ClipboardContentBinding);
			e.ClipboardRowContent.Add(new DataGridClipboardCellContent(e.Item, dtg.CurrentColumn, cellValue));
		}

		private ContentControl ClipboardContentControl
		{
			get
			{
				if (this._clipboardContentControl == null)
					this._clipboardContentControl = new ContentControl();
				return this._clipboardContentControl;
			}
		} ContentControl _clipboardContentControl;

		private object GetCellValue(object item, System.Windows.Data.Binding binding)
		{
			object cellValue = null;
			if (binding != null)
			{
				ClipboardContentControl.DataContext = item;
				ClipboardContentControl.SetBinding(ContentControl.ContentProperty, binding);
				cellValue = ClipboardContentControl.GetValue(ContentControl.ContentProperty);
			}
			return cellValue;
		}
	}
	#endregion
}
